<template>
  <div class="app-container">
    <div style="margin-bottom: 20px; text-align: center">
      <h2>{{ title }}</h2>
    </div>
    <el-divider/>
    <div style="display: flex; justify-content: space-between">
      <div style="width: 49%">
        <el-table ref="table" v-loading="loading" :data="questionList" size="mini" border height="750"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="题目" prop="topic"/>
          <el-table-column label="标签" width="160px" sortable prop="tag" :filters="tagFilters"
                           :filter-method="filterTag" align="center" :formatter="tagTransform" />
          <el-table-column label="类型" width="100px" prop="type" sortable align="center" :filters="dictFilters"
                           :filter-method="filterType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.exam_question_type" :value="scope.row.type" size="mini"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="width: 49%">
        <el-form ref="formRef" :model="params" label-position="top" :rules="formRules">
          <el-form-item label="试卷总分" prop="name">
            <el-input-number disabled style="width: 100%" v-model="params.fraction" :precision="1" :min="0"/>
          </el-form-item>
          <el-form-item label="合格分数" prop="passFraction">
            <el-input-number style="width: 100%" v-model="params.passFraction" :precision="1" :min="0"
                             :max="params.fraction"/>
          </el-form-item>
          <el-form-item label="试卷名称" prop="name">
            <el-input v-model="params.name" placeholder="请输入试卷名称"/>
          </el-form-item>
          <el-form-item label="试卷描述" prop="description">
            <html-editor style="max-height: 200px" :value="params.description" @update:input="getDescription"/>
            <!-- <Tinymce :value="params.description"/> -->
          </el-form-item>
          <el-form-item label="试题配置" prop="questions">
            <el-empty v-if="params.questions.length === 0" description="暂无选择的试题"></el-empty>
            <div v-else style="max-height: 600px; overflow: auto; width: 100%;">
              <div v-for="(item,index) in params.questions" style="display: flex; justify-content: space-between">
                <el-row>
                  <el-col :span="20">
                    <div style="display: flex; align-items: center;">
                      <div style="width: 30px">{{ index + 1 }}.</div>
                      <dict-tag style="margin-right: 5px; width: 60px" :options="dict.type.exam_question_type"
                                :value="item.type"
                                size="mini"/>
                      <span>
                      <div style="width: 580px;white-space: nowrap; overflow: hidden; text-overflow: ellipsis">
                        {{ item.topic }}
                      </div>
                  </span>
                    </div>
                  </el-col>
                  <el-col :span="4">
                    <div>
                      <el-input-number v-model="item.score" :precision="1" :min="1" :max="100"
                                       size="mini"/>
                    </div>
                  </el-col>
                </el-row>

              </div>
            </div>
          </el-form-item>
        </el-form>
        <div style="text-align: right; margin-top: 20px">
          <el-button @click="cancel">
            取 消
          </el-button>
          <el-button type="primary" @click="submitForm">
            保 存
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import {testPaperAddOrUpdate, testPaperInfo} from "@/api/exam/testPaper";
import {getQuestionTags, pageList} from "@/api/exam/questionLibrary";
import HtmlEditor from "@/components/HtmlEditor/index.vue";
import Tinymce from "@/components/tinymce/index.vue";
import {tagList} from "@/api/edu/trainPlan";

export default {
  name: 'ExamTestPaperOption',
  dicts: ['exam_question_type'],
  components: {HtmlEditor,Tinymce},
  data() {
    const checkQuestions = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error('请选择至少一道试题'))
      } else {
        callback()
      }
    };
    return {
      title: '新建试卷',
      loading: false,
      questionShow: false,
      questionList: [],
      questionQueryParams: {
        pageNum: 1,
        pageSize: 9999
      },
      params: {
        name: '',
        description: '',
        fraction: 0,
        passFraction: 0,
        questions: []
      },
      formRules: {
        name: [{
          required: true, message: '请输入试卷名称', trigger: 'blur'
        }],
        questions: [{
          required: true, validator: checkQuestions, trigger: 'blur'
        }]
      },
      dictFilters: [],
      tagFilters: []
    }
  },
  created() {
    const id = this.$route.query.id
    if (id) {
      this.title = '编辑试卷'
      this.getInfo(id)
    }
    this.getQuestionList()
  },
  watch: {
    "params.questions": {
      handler() {
        this.params.fraction = 0
        this.params.questions.forEach(q => {
          this.params.fraction += q.score
        })
      },
      deep: true
    }
  },
  methods: {
    filterTag(value, row) {
      // 如果 row.tag 存在，则将其分割成数组
      if (row.tag) {
        const tagSplit = row.tag.split(',');
        // 检查分割后的数组中是否包含筛选值
        return tagSplit.includes(value);
      }
      return false;
    },
    filterType(value, row) {
      console.log(row)
      console.log(value)
      return row.type === value;
    },
    tagTransform(row) {
      if (row.tag){
        const tagSplit = row.tag.split(',')
        let tags = [];
        tagSplit.forEach(t => {
          this.tagFilters.forEach(tag => {
            if (tag.value === t){
              tags.push(tag.text)
            }
          })
        })
        return tags.join(' | ')
      } else {
        return ""
      }
    },
    getInfo(id) {
      testPaperInfo(id, 1).then(res => {
        this.params = res.data
      })
    },
    getQuestionList() {
      this.loading = true
      pageList({
        pageNum: 1,
        pageSize: 9999
      }).then(res => {
        this.tagFilters = []
        this.dictFilters = []
        this.dict.type.exam_question_type.forEach(d => {
          this.dictFilters.push({
            text: d.label,
            value: d.value
          })
        })
        getQuestionTags().then(res => {
          tagList().then(res => {
            res.data.forEach(d => {
              this.tagFilters.push({
                text: d.tagName,
                value: d.id
              })
            })
          })
        })
        this.questionList = res.rows
        this.loading = false
        this.$nextTick(() => {
          this.params.questions.forEach(q => {
            const row = this.questionList.find(a => a.id === q.id)
            if (row) {
              this.$refs.table.toggleRowSelection(row)
            }
          })
        })
      })
    },
    handleSelectionChange(selection) {
      this.params.questions = []
      selection.forEach(s => {
        s.score = 1
        this.params.questions.push(s)
      })
      this.params.questions.sort((a, b) => a.type - b.type)
    },
    cancel() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.back()
    },
    getDescription(e) {
      this.params.description = e
    },
    submitForm() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const h = this.$createElement;
          this.$msgbox({
            title: '确认保存',
            message: h('p', null, [
              h('div', null, `本试卷共【${this.params.questions.length}】道题`),
              h('div', null, `总分：【${this.params.fraction}】分`)
            ]),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(() => {
            testPaperAddOrUpdate(this.params).then(() => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.cancel()
            })
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
